package db

import (
	"fmt"
	"my-systems/pet-system/internal/models"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/plugin/dbresolver"
	config "my-systems/pet-system/configs"
)

var DB *gorm.DB

func init() {
	if config.DBHost == "" {
		panic("数据库配置未加载，请先调用 config.LoadConfig()")
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.DBUser,
		config.DBPassword,
		config.DBHost,
		config.DBPort,
		config.DBName,
	)

	// 初始化主数据库连接（写操作）
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect to database: " + err.Error())
	}

	// 配置读写分离
	err = DB.Use(dbresolver.Register(dbresolver.Config{
		Sources:  []gorm.Dialector{mysql.Open(dsn)}, // 写库（主库）
		Replicas: []gorm.Dialector{mysql.Open(dsn)}, // 读库（从库），实际生产应使用不同DSN
		Policy:   dbresolver.RandomPolicy{},         // 读库负载均衡策略
	}))
	if err != nil {
		panic("failed to setup database resolver: " + err.Error())
	}

	// 获取底层SQL DB连接池
	sqlDB, err := DB.DB()
	if err != nil {
		panic("failed to get underlying sql.DB: " + err.Error())
	} else if err = sqlDB.Ping(); err != nil {
		panic("数据库连接测试失败: " + err.Error())
	}

	// 配置连接池参数
	sqlDB.SetMaxOpenConns(config.DBMaxOpenConnections)
	sqlDB.SetMaxIdleConns(config.DBMaxIdleConnections)
	lifeTime, err := time.ParseDuration(config.DBMaxConnectionLifeTime)
	if err != nil {
		panic("invalid max connection life time: " + err.Error())
	}
	sqlDB.SetConnMaxLifetime(lifeTime)

	fmt.Println("数据库初始化成功，已启用读写分离")

	Migration()

}

func Migration() {
	// 注意：迁移操作会自动使用写库
	err := DB.Set("gorm:table_options", "charset=utf8mb4").
		AutoMigrate(
			// 添加需要迁移的模型
			&models.User{},
			&models.Pet{},
			&models.PetPhotos{},
			&models.PetsAreAvailableForSale{},
			&models.Foster{},
		)
	if err != nil {
		panic("数据库迁移失败: " + err.Error())
	}
	fmt.Println("数据迁移成功")
}
